package com.wanchuang.hepos.ui;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.huawei.hms.hmsscankit.ScanUtil;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.help.DialogUtils;
import com.wanchuang.hepos.help.UserHelper;
import com.wanchuang.hepos.ui.base.BaseActivity;


public class LoginActivity extends BaseActivity {

    private NavController nav;
    private long mExitTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        nav = Navigation.findNavController(this, R.id.main_fragment_host);
        mSharedViewModel.isShowLoginOut.observe(this, aBoolean -> {
            if (aBoolean) {
                DialogUtils.showDefaultDialog(LoginActivity.this, "提示", "是否退出登录", new DialogUtils.DialogImpl() {
                    @Override
                    public void onOk() {
                        UserHelper.loginOut();
                        nav.popBackStack(R.id.loginFragment, false);
                    }
                });
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (nav.getCurrentDestination() != null) {
            switch (nav.getCurrentDestination().getId()) {
                case R.id.loginFragment:
                    if (System.currentTimeMillis() - mExitTime > 2000) {
                        showShortToast("再按一次退出程序");
                        mExitTime = System.currentTimeMillis();
                    } else {
                        super.onBackPressed();
                    }
                    break;
                case R.id.forgetPasswordFragment:
                case R.id.registerFragment:
                case R.id.MCCSelectFragment:
                case R.id.placeSelectFragment:
                    super.onBackPressed();
                    break;
                default:
                    mSharedViewModel.isShowLoginOut.setValue(true);
            }
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //当扫码页面结束后，处理扫码结果
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }

        mSharedViewModel.sn.setValue(data.getStringExtra(ScanUtil.RESULT));
    }
}
